<?php

namespace Roles\Controller;

use Zend\Mvc\Controller\AbstractActionController,
    Zend\View\Model\ViewModel;

class RolesController extends AbstractActionController {

   protected $usuarioTable;

   private function checkLogin() {
      if (! $this->getServiceLocator()
                 ->get('AuthService')->hasIdentity()){
         return $this->redirect()->toRoute('login');
      }
   }
   private function checkRole() {
      $username = $this->getServiceLocator()->get('AuthService')->getIdentity();
      $usuario = $this->getUsuarioTable()->getUsuarioByUserName($username);

      $path = $this->getRequest()->getUri()->getPath();
      if ($path[0] != '/') $path = '/' . $path;
      $pieces = explode("/",$path);
      $module = $pieces[1]; $action = $pieces[2];
      if ($action == "") $action = "index";

      if (! $this->getServiceLocator()
                 ->get('RoleService')->hasPermission($usuario->id,$module,$action)) {

         return $this->redirect()->toRoute('restringido');
      }
   }

   public function indexAction() {

      $this->checkLogin();
      $this->checkRole();

      return new ViewModel();
   }

   public function getUsuarioTable() {
      if (!$this->usuarioTable) {
         $sm = $this->getServiceLocator();
         $this->usuarioTable = $sm->get('Usuarios\Model\UsuarioTable');
      }
      return $this->usuarioTable;
   }


}
